package definite.Guide.Book.JOptionPane;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public final class OptionPaneUtils {

	public OptionPaneUtils() {

	}

	public static int getSelection(JOptionPane optionPane) {
		// default return value , it is nothing selected
		int returnValue = JOptionPane.CLOSED_OPTION;

		// get selected value
		Object selectedValue = optionPane.getValue();
		Object options[] = optionPane.getOptions();
		if (selectedValue != null) {
			if (options == null)
				// default button , no array specified
				if (selectedValue instanceof Integer)
					returnValue = ((Integer) selectedValue).intValue();
		} else
			// Array of option button , specified
			for (int i = 0; i < options.length; i++)
				if (options[i].equals(selectedValue)) {
					returnValue = i;
					break;
				}

		return returnValue;
	}

	public static JOptionPane
			getNarrowOptionPane(int maxCharactersPerLineCount) {
		// Our inner class definition
		class NarrowOptionPane extends JOptionPane {
			int maxCharactersPerLineCount;

			NarrowOptionPane(int maxCharactersPerLineCount) {
				this.maxCharactersPerLineCount = maxCharactersPerLineCount;
			}

			@Override
			public int getMaxCharactersPerLineCount() {
				return maxCharactersPerLineCount;
			}
		}
		return new NarrowOptionPane(maxCharactersPerLineCount);
	}

	public static JSlider getSlider(final JOptionPane pane) {
		JSlider slider = new JSlider();
		slider.setMajorTickSpacing(10);
		slider.setPaintTicks(true);
		slider.setPaintLabels(true);

		ChangeListener changeListener = new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				JSlider sl = (JSlider) e.getSource();
				if (!sl.getValueIsAdjusting())
					pane.setInputValue(new Integer(sl.getValue()));
			}
		};

		slider.addChangeListener(changeListener);
		return slider;
	}

	public static JButton getButton(final JOptionPane pane, String text,
									Icon icon) {
		final JButton button = new JButton(text, icon);
		ActionListener listener = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				pane.setValue(button.getText());
			}
		};
		button.addActionListener(listener);
		return button;
	}

}
